package com.hrt.util;

import java.util.List;

import javax.annotation.Resource;
import javax.annotation.Resources;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.hrt.bean.Sequence;

@Transactional
@Repository
public class GenarateDao extends SuperDao {
	



	
	
	
	public void setSession(SessionFactory session) {
		super.setSessionFactory(session);
	}

	/**
	 * 
	 * @param entityName
	 * @return
	 */
	public synchronized  Sequence queryMaxId(String entityName)
	{
		Long maxId=0l;
		String hql="from Sequence seq where seq.tableName='"+entityName+"'";
		List list=this.getHibernateTemplate().find(hql);
		if(list!=null && !list.isEmpty())
		{
			Sequence seq=(Sequence) list.get(0);
			
			return seq;
		}
		return null;
		
	}

	/**
	 * 
	 * @param seq
	 */

	public void updateMaxId(Sequence seq) {
		// TODO Auto-generated method stub
	getHibernateTemplate().update(seq);
		System.out.println("maxId has update..");
	}
	/**
	 * 
	 * @param entityName
	 * @return
	 */
	public synchronized  Sequence getNextSequence(String entityName){
		Long nextId=0l;
		Sequence seq=queryMaxId(entityName);
		nextId=seq.getMaxId()+1;
		seq.setMaxId(nextId);
		updateMaxId(seq);
		return seq;
	}
	
}
